package com.dianjing.dianjing.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dianjing.dianjing.dto.input.InformInput;
import com.dianjing.dianjing.entity.Inform;
import com.dianjing.dianjing.mapper.InformMapper;
import com.dianjing.dianjing.service.InformService;
import com.dianjing.dianjing.util.DataUtils;
import com.dianjing.dianjing.util.MapUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 通知表 服务实现类
 * </p>
 *
 * @author LBG
 * @since 2022-11-09
 */
@Service
public class InformServiceImpl extends ServiceImpl<InformMapper, Inform> implements InformService {

    /**
     * 发布通知
     *
     * @param input
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public DataUtils publishInform(InformInput input) {
        QueryWrapper<Inform> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Inform::getNotifierId,input.getNotifierId())
                .eq(Inform::getNotifiedPartId,input.getNotifiedPartId());
        List<Inform> list = this.list(wrapper);

        // 校验
        for (Inform inform : list) {
            if(DateUtil.beginOfDay(new Date()).equals(inform.getCreateTime())){
                return DataUtils.error("您今天已经通知过对方了，请明日在试");
            }
        }

        // 入库
        Inform map = MapUtil.map(input, Inform.class);
        map.setCreateTime(DateUtil.beginOfDay(new Date()));
        map.setCreateTime(new Date());
        this.save(map);
        return DataUtils.ok(list);
    }



    /**
     * 查看通知
     *
     * @param userId
     * @return
     */
    @Override
    public DataUtils showInform(Long userId) {
        QueryWrapper<Inform> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Inform::getNotifiedPartId,userId);
        List<Inform> list = this.list(wrapper);
        return DataUtils.ok(list);
    }

    /**
     * 根据id查看通知详情
     *
     * @param informId
     * @return
     */
    @Override
    public DataUtils showInformDetail(Long informId) {
        return DataUtils.ok(this.getById(informId));
    }

    @Override
    public Boolean removeInfo(Long infoId) {
        // 删除
        int i = baseMapper.deleteById(infoId);
        return i >= 1;
    }
}
